package com.bbcare.followup.plat.controller;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bbcare.comm.AppException;
import com.bbcare.comm.Constants;
import com.bbcare.comm.DateUtil;
import com.bbcare.comm.ErrorCode;
import com.bbcare.comm.OSSClientUtil;
import com.bbcare.comm.PropertiesUtils;
import com.bbcare.comm.QueryModel;
import com.bbcare.comm.ResultModel;
import com.bbcare.comm.SeqUtil;
import com.bbcare.comm.ToolUtils;
import com.bbcare.department.plat.service.IBsStaticParamService;
import com.bbcare.followup.plat.entity.FollowQueue;
import com.bbcare.followup.plat.entity.FollowQueueAuthority;
import com.bbcare.followup.plat.entity.PatientQueueScheme;
import com.bbcare.followup.plat.service.IFollowQueueService;
import com.bbcare.followup.plat.service.IPatientQueueService;

/*
 * @name:         队列信息控制类
 * @author:       DemonLee
 * @createTime:   2017.4.12
 * @description:  队列信息相关操作
 * @modify:
 *
 */
@Controller
@RequestMapping("/service/queue")
public class QueueController {
    private final Log logger = LogFactory.getLog(QueueController.class);
    @Autowired
    private IFollowQueueService followQueueSerivce;

    @Autowired
    private IPatientQueueService patientQueueService;

    // @Autowired
    // private IPatientService patientSerivce;

    @Autowired
    private IBsStaticParamService bsStaticParamService;

    @ResponseBody
    @RequestMapping("/patient")
    public ResultModel<PatientQueueScheme> getQueuePatient(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.info("in getQueuePatient----arg==" + arg);
        JSONObject jsonEsb = JSON.parseObject(arg);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }
        String queueId = requestParam.getString("queueId");
        if (StringUtils.isEmpty(queueId)) {
            logger.debug("out getDoctorBasicDetail----arg== null");
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "参数校验失败，队列ID不能为空");
        }

        List<PatientQueueScheme> patients = followQueueSerivce.getPatientListByQueueId(requestParam);
        if (!CollectionUtils.isEmpty(patients)) {
            logger.info("out getDoctorBasicDetail----arg==" + patients.get(0));
            return new ResultModel<PatientQueueScheme>(patients.get(0));
        } else {
            return new ResultModel<PatientQueueScheme>(null);
        }

    }

    @ResponseBody
    @RequestMapping("/detail")
    public ResultModel<FollowQueue> getQueueDetail(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.info("in getQueueDetail----arg==" + arg);
        JSONObject jsonEsb = JSON.parseObject(arg);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }
        String queueId = requestParam.getString("queueId");
        if (StringUtils.isEmpty(queueId)) {
            logger.debug("out getQueueDetail----arg== null");
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "队列ID不能为空");
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", queueId);
        FollowQueue queue = followQueueSerivce.getQueueDetailByQueueId(map);
        logger.info("out getQueueDetail----arg==" + queue);
        return new ResultModel<FollowQueue>(queue);
    }

    // 队列信息List查询
    @ResponseBody
    @RequestMapping("/followQueueListQuery")
    public ResultModel<HashMap<String, Object>> getFollowQueueList(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.warn("in getFollowQueueList----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            // 后续重写异常类
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参节点错误，非json格式！"));
        }
        HashMap<String, Object> paramMap = new HashMap<String, Object>();
        JSONObject jsonData = jsonArg.getJSONObject("data");
        if (null == jsonData) {
            logger.warn("in getFollowQueueList----no data node...");
            // 前台必须传data节点，否则报错返回（后续重写异常类）
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }
        paramMap.putAll(jsonData);
        int page = jsonData.getIntValue("page");
        int rows = jsonData.getIntValue("rows");
        if (page > 0 && rows > 0) {
            paramMap.put("start", (page - 1) * rows);
            paramMap.put("end", rows);
        }

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String authorId = (String) sessionMap.get("authorId");
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
//        String deptId = sessionMap.get("deptId") == null ? "":String.valueOf(sessionMap.get("deptId"));// 租户id

        paramMap.put("authorId", authorId);
        paramMap.put("queueStatus", Constants.QUEUE_STATUS_NOMAL);
        paramMap.put("queueTypeTenant", Constants.QUEUE_TYPE_TENANT);
        paramMap.put("queueTypePublic", Constants.QUEUE_TYPE_PUBLIC);
        paramMap.put("queueTypePrivate", Constants.QUEUE_TYPE_PRIVATE);
        String objectStr = jsonData.getString("queueName");
        String queueName = StringUtils.isBlank(objectStr) ? objectStr : "%" + objectStr + "%";

        paramMap.put("queueName", queueName);
        if (null != tenantId) {
            paramMap.put("tenantId", tenantId.toString());
        }
        String showFlag = jsonData.getString("showFlag");
        if(!StringUtils.isBlank(showFlag)) {
        	paramMap.put("showFlag", showFlag);
        }
        HashMap<String, Object> retOut = followQueueSerivce.getQueueList(paramMap);
        return new ResultModel<HashMap<String, Object>>(retOut);
    }

    // 队列增加修改
    @ResponseBody
    @RequestMapping("/modify")
    public ResultModel<HashMap<String, String>> saveQueueInfo(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.warn("in saveQueueInfo----arg==" + arg.toString());
        JSONObject jsonEsb = JSON.parseObject(arg);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

        String queueStr = requestParam.getString("queueInfo");
        if (null == queueStr) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，queueInfo节点！");
        }

        String queueAuthoritys = requestParam.getString("queueAuthoritys");

        List<FollowQueueAuthority> authoritys = null ;
        if (null != queueAuthoritys) {
        	authoritys = JSON.parseArray(queueAuthoritys, FollowQueueAuthority.class);
        }

        FollowQueue followQueue = JSON.parseObject(queueStr, FollowQueue.class);

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String authorId = (String) sessionMap.get("authorId");
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        String deptId = sessionMap.get("deptId") == null ? "":String.valueOf(sessionMap.get("deptId"));// 租户id

        if (null == authorId || StringUtils.isBlank(String.valueOf(authorId))) {
            logger.warn("authorId is null");
            followQueue.setAuthorId("001");
        } else {
            followQueue.setAuthorId(String.valueOf(authorId));
        }

        followQueue.setTenantId(tenantId.toString());

        //科室id 放入队列
        followQueue.setDeptId(deptId);

        Map<String,Object> map = new HashMap<String,Object>();
        map.put("followQueue",followQueue);
        map.put("authorId",authorId);
        if(!CollectionUtils.isEmpty(authoritys)){
        	map.put("queueAuthoritys",authoritys);
        }
        String id = followQueueSerivce.queueModify(map);

        HashMap<String, String> userMap = new HashMap<String, String>();
        userMap.put("queueId", id);
        return new ResultModel<HashMap<String, String>>(userMap);
    }

    // 队列权限修改
    @ResponseBody
    @RequestMapping("/authority/modify")
    public ResultModel<Map<String, String>> modifyQueueAuthority(@RequestBody String arg,
            HttpServletRequest request) throws Exception {
        logger.warn("in queueAuthorityModify----arg==" + arg.toString());
        JSONObject jsonEsb = JSON.parseObject(arg);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

        String queueAuthoritys = requestParam.getString("queueAuthoritys");
        if (null == queueAuthoritys) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
                    "参数校验失败，queueAuthoritys节点不能为空");
        }

        String queueId = requestParam.getString("queueId");
        if (null == queueId) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "参数校验失败，队列ID不能为空");
        }
        List<FollowQueueAuthority> authoritys = JSON.parseArray(queueAuthoritys, FollowQueueAuthority.class);

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String authorId = (String) sessionMap.get("authorId");

        // 设置创建人
        String sysdate = DateUtil.getSysDateA();
        for (int i = 0; i < authoritys.size(); i++) {
            authoritys.get(i).setCreateTime(sysdate);
            authoritys.get(i).setId(SeqUtil.getSeqNo());
            authoritys.get(i).setQueueId(queueId);
            authoritys.get(i).setCreateAuthor(String.valueOf(authorId));
            authoritys.get(i).setStatus(Constants.TABLE_RECORD_STATUS_NOMAL);
        }

        followQueueSerivce.queueAuthorityModify(authoritys);
        HashMap<String, String> userMap = new HashMap<String, String>();
        return new ResultModel<Map<String, String>>(userMap);
    }

    // 删除队列
    @ResponseBody
    @RequestMapping("/remove")
    public ResultModel<Object> deleteQueue(@RequestBody String jsonStr, HttpServletRequest request) throws Exception {
        logger.info("in deleteContact----arg==" + jsonStr);
        JSONObject jsonEsb = JSON.parseObject(jsonStr);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }
        String id = requestParam.getString("queueId");

        if (StringUtils.isEmpty(id)) {
            // 返回空 或者返回校验失败
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "参数校验失败，要删除的队列ID不能为空");
        }

        // List<String> list = JSON.parseArray(ids, String.class);
        /*
         * if(CollectionUtils.isEmpty(list)){
         * logger.debug("out deleteContact----arg== null"); return new
         * ResultModel<DepartmentBasic>(null); }
         */
        // 判断队列是否还有患者
        List<PatientQueueScheme> patients = followQueueSerivce.getPatientListByQueueId(requestParam);

        if (!CollectionUtils.isEmpty(patients)) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_QUEUE_HAVE_MANAGERPATIENTS,
                    "队列中有正在管理的患者，请转移全部患者后删除");
        }

        followQueueSerivce.QueueDeleteById(requestParam);
        logger.info("out queueDelete----arg==");
        return new ResultModel<Object>(null);
    }

    // 队列管理员转让
    @ResponseBody
    @RequestMapping("/authority/admintransfer")
    public ResultModel<Object> transferQueueAdmin(@RequestBody String jsonStr, HttpServletRequest request)
            throws Exception {
        logger.info("in queueAdminTransfer----arg==" + jsonStr);
        JSONObject jsonEsb = JSON.parseObject(jsonStr);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }
        String queueId = requestParam.getString("queueId");
//        String fromDoctorId = requestParam.getString("fromDoctorId");// 从SESSION获取
        String toDoctorId = requestParam.getString("toDoctorId");
        if (StringUtils.isEmpty(toDoctorId) || StringUtils.isEmpty(queueId)) {
            // 返回校验失败 参数校验失败
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
                    "参数校验失败，toDoctorId|fromDoctorId|queueId不能为空");
        }

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String authorId = (String) sessionMap.get("authorId");
        requestParam.put("authorId", authorId);
        followQueueSerivce.queueAdminTransfer(requestParam);
        // PatientQueueScheme patient =
        // followQueueSerivce.getPatientListByQueueId(requestParam);

        logger.info("out queueAdminTransfer----arg==");
        return new ResultModel<Object>(null);
    }

    // 查询出科室(后续增加团队 租户)下所有医生 和 所属队列的角色
    @ResponseBody
    @RequestMapping("/authority/doctors")
    public ResultModel<Object> queueDoctorRolesByCondition(@RequestBody String jsonStr, HttpServletRequest request)
            throws Exception {
        logger.info("in queueDoctorRolesByCondition----arg==" + jsonStr);
        JSONObject jsonEsb = JSON.parseObject(jsonStr);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

        // Object deptId = session.getAttribute("deptId");
        // String doctorId = requestParam.getString("doctorId");

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String doctorId = (String) sessionMap.get("authorId");
//        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        String deptId = (String) sessionMap.get("deptId");// 科室id

        String docorName = requestParam.getString("doctorName");
        docorName = StringUtils.isBlank(docorName) ? null : "%" + docorName + "%";

        String queueId = requestParam.getString("queueId");
        /*if (StringUtils.isEmpty(queueId)) {
            // 返回校验失败 参数校验失败
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "参数校验失败，队列ID不能为空");
        }*/

        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("doctorId", doctorId);
        paramMap.put("deptId", deptId);// deptId 从session获取
        paramMap.put("doctorName", docorName);
        paramMap.put("queueId", queueId);

        List<Map<String, Object>> resultList = followQueueSerivce.queueDoctorsQuery(paramMap);

        Map<String, Object> param = new HashMap<String, Object>();
        param.put("deptId", deptId);
        param.put("type", Constants.DOCTOR_TITLE_TYPE_CODE);
        Map<String, String> titleMap = bsStaticParamService.getStaticParamsForMap(param);

        param.put("type", Constants.QUEUE_DOCTOR_ROLE_TYPE_CODE);
        Map<String, String> roleMap = bsStaticParamService.getStaticParamsForMap(param);
        // 拼医生职称中文名字和 角色名称
        Map<String, Object> mapTemp = null;
        if (!CollectionUtils.isEmpty(resultList)) {
            for (int i = 0; i < resultList.size(); i++) {
                mapTemp = resultList.get(i);
                resultList.get(i).put("doctorTitleName", titleMap.get(mapTemp.get("doctorTitle")));
                resultList.get(i).put("roleName", roleMap.get(mapTemp.get("role")));
            }
        }

        logger.info("out queueDoctorRolesByCondition----arg==");
        return new ResultModel<Object>(resultList);
    }

    // 查询出当前队列所有管理
    @ResponseBody
    @RequestMapping("/authority/teams")
    public ResultModel<Object> getQueueManagerDoctors(@RequestBody String jsonStr, HttpServletRequest request)
            throws Exception {
        logger.info("in queueManagerDoctors----arg==" + jsonStr);
        JSONObject jsonEsb = JSON.parseObject(jsonStr);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String doctorId = (String) sessionMap.get("authorId");
//        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        String deptId = (String) sessionMap.get("rootGroupId");// 科室id

        String queueId = requestParam.getString("queueId");

        if (StringUtils.isEmpty(queueId)) {
            // 返回校验失败 参数校验失败
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "参数校验失败，队列ID不能为空");
        }
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("doctorId", doctorId);
        paramMap.put("queueId", queueId);

        List<Map<String, Object>> resultList = followQueueSerivce.queuemanagerDoctors(paramMap);

        Map<String, Object> param = new HashMap<String, Object>();
        param.put("deptId", deptId);
        param.put("type", Constants.QUEUE_DOCTOR_ROLE_TYPE_CODE);
        Map<String, String> roleMap = bsStaticParamService.getStaticParamsForMap(param);
        // 拼医生职称中文名字和 角色名称
        Map<String, Object> mapTemp = null;
        if (!CollectionUtils.isEmpty(resultList)) {
            for (int i = 0; i < resultList.size(); i++) {
                mapTemp = resultList.get(i);
                resultList.get(i).put("roleName", roleMap.get(mapTemp.get("role")));
            }
        }

        // PatientQueueScheme patient =
        // followQueueSerivce.getPatientListByQueueId(requestParam);
        logger.info("out queueManagerDoctors----arg==");
        return new ResultModel<Object>(resultList);
    }

    // 审核记录分页查询
    @ResponseBody
    @RequestMapping("/auditTask/list")
    public QueryModel<Map<String, Object>> getAuditTaskList(@RequestBody String arg) throws Exception {
        logger.warn("in getAuditTaskList----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            logger.error("json转换异常", ex);
            // 后续重写异常类
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "非json格式");
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            logger.warn("in getAuditTaskList----no data node...");
            // 前台必须传data节点，否则报错返回（后续重写异常类）
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

        String queueId = jsonData.getString("queueId");
        if (null == queueId) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "参数校验失败，队列ID不能为空");
        }

        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.putAll(jsonData);
        List<Map<String, Object>> auditList = patientQueueService.patientAuditRecordList(paramMap);
        int total = patientQueueService.patientAuditRecordCount(paramMap);
        return new QueryModel<Map<String, Object>>(auditList, total);
    }

    // 审核记录分页查询
    @ResponseBody
    @RequestMapping("/auditTask/modify")
    public ResultModel<Object> modifyAuditTask(@RequestBody String arg) throws Exception {
        logger.warn("in auditTaskModify----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            // 后续重写异常类
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "非json格式");
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            logger.warn("in getAuditTaskList----no data node...");
            // 前台必须传data节点，否则报错返回（后续重写异常类）
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

        String queueId = jsonData.getString("queueId");
        String status = jsonData.getString("status");
        String userId = jsonData.getString("userId");
        String auditId = jsonData.getString("auditId");

        if (null == queueId || null == status || null == userId || null == auditId) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
                    "参数校验失败，队列ID|审核状态|患者ID不能为空");
        }

        // TODO从session中获取 authorId

        HashMap<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.putAll(jsonData);
        paramMap.put("authorId", "001");//
        patientQueueService.updateAuditTask(paramMap);

        return new ResultModel<Object>(null);
    }

    // 当前登录账号队列患者主页统计数据
    @ResponseBody
    @RequestMapping("/queueHomeStatistics")
    public ResultModel<Map<String, Object>> getQueueHomeStatistics(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.warn("in qryQueueHomeStatistics----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            // 后续重写异常类
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "非json格式"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            logger.warn("in qryQueueHomeStatistics----no data node...");
            // 前台必须传data节点，否则报错返回（后续重写异常类）
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

        String queueId = jsonData.getString("queueId");
        if (StringUtils.isEmpty(queueId)) {
            logger.warn("in qryQueueHomeStatistics----no queueId node...");
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，队列ID不能为空");
        }

        HashMap<String, Object> paramMap = new HashMap<String, Object>(jsonData);
        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String authorId = (String) sessionMap.get("authorId");
//        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        String deptId = (String) sessionMap.get("rootGroupId");// 科室id

        paramMap.put("authorId", authorId);
        paramMap.put("deptId", deptId);

        Map<String, Object> retMap = followQueueSerivce.qryQueueHomeStatistics(paramMap);
        return new ResultModel<Map<String, Object>>(retMap);
    }

    // 当前登录账号队列患者各种增长趋势统计数据
    @ResponseBody
    @RequestMapping("/trenddataStatistics")
    public ResultModel<List<Map<String, Object>>> trendDataStatistics(@RequestBody String arg,
            HttpServletRequest request) throws Exception {
        logger.warn("in trenddataStatistics----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            // 后续重写异常类
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "非json格式"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);

        if (null == jsonData) {
            logger.warn("in trenddataStatistics----no data node...");
            // 前台必须传data节点，否则报错返回（后续重写异常类）
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

        String queueId = jsonData.getString("queueId");
        if (StringUtils.isEmpty(queueId)) {
            logger.warn("in qryQueueHomeStatistics----no queueId node...");
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，队列ID不能为空");
        }

        String busiType = jsonData.getString("busiType");
        String dateType = jsonData.getString("dateType");

        if (StringUtils.isBlank(busiType)) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，busiType不能为空");

        }
        if (StringUtils.isBlank(dateType)) {
            dateType = "1"; // 默认查最近7天数据
        }

        Map<String, Object> paramMap = new HashMap<String, Object>(jsonData);
        paramMap.put("dateType", dateType);

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String authorId = (String) sessionMap.get("authorId");
        paramMap.put("authorId", authorId);

        List<Map<String, Object>> list = followQueueSerivce.qryTrenddataStatistics(paramMap);
        return new ResultModel<List<Map<String, Object>>>(list);
    }

    /**
     * 某一队列下孕周数据统计
     *
     * @param arg
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/pregnancyStatistics")
    public ResultModel<Map<String, Object>> getPregnancyStatistics(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.warn("in getPregnancyStatistics----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            // 后续重写异常类
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "非json格式"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);

        if (null == jsonData) {
            logger.warn("in getPregnancyStatistics----no data node...");
            // 前台必须传data节点，否则报错返回（后续重写异常类）
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

        Map<String, Object> paramMap = new HashMap<String, Object>(jsonData);

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String authorId = (String) sessionMap.get("authorId");
        paramMap.put("authorId", authorId);

        Map<String, Object> map = followQueueSerivce.getPregnancyStatistics(paramMap);

        return new ResultModel<Map<String, Object>>(map);
    }

    /**
     *
     * @param arg
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/patientSourceStatistics")
    public ResultModel<Map<String, Object>> patientSourceStatistics(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.warn("in patientSourceStatistics----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            // 后续重写异常类
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "非json格式"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);

        if (null == jsonData) {
            logger.warn("in patientSourceStatistics----no data node...");
            // 前台必须传data节点，否则报错返回（后续重写异常类）
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

        Map<String, Object> paramMap = new HashMap<String, Object>(jsonData);

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String authorId = (String) sessionMap.get("authorId");
        paramMap.put("authorId", authorId);

        Map<String, Object> map = followQueueSerivce.getPatientResourceStatistics(paramMap);

        return new ResultModel<Map<String, Object>>(map);
    }

    /**
     * 队列logo上传
     *
     * @param response
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/uploadQueueLogo")
    public ResultModel<Object> uploadQueueLogo(HttpServletResponse response, HttpServletRequest request)
            throws Exception {
        String filepath = "";
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        if (multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Iterator<String> iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                MultipartFile file = multiRequest.getFile(iter.next());
                if (!file.isEmpty()) {
                    filepath = OSSClientUtil.uploadPicture(file, PropertiesUtils.getProperty("queueLogo"));// 保存图片
                }
            }
        }
        return new ResultModel<Object>(filepath);
    }

    /**
     * 科室医生职称列表
     *
     * @param request
     * @param jsonStr
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/authority/rolelist")
    public ResultModel<List<Map<String, Object>>> getRolelist(HttpServletRequest request, @RequestBody String jsonStr)
            throws Exception {
        logger.info("in getScheduleTypeList----arg==" + jsonStr);
        JSONObject jsonEsb = JSON.parseObject(jsonStr);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }
        //
        Map<String, Object> paramTemp = new HashMap<String, Object>();

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String tenantId = (String) sessionMap.get("tenantId");// 租户id

        paramTemp.put("deptId", tenantId);
        paramTemp.put("type", Constants.QUEUE_DOCTOR_ROLE_TYPE_CODE);
        List<Map<String, Object>> list = bsStaticParamService.getStaticParamsByCondition(paramTemp);
        logger.info("out getDoctorTitleList----arg==" + list);
        return new ResultModel<List<Map<String, Object>>>(list);
    }

    // 某个队列建档问卷查询
    @ResponseBody
    @RequestMapping("/patientAddContentQuery")
    public ResultModel<Map<String, Object>> qryPatientAddContent(@RequestBody String arg) throws Exception {
        logger.warn("in patientAddContentQuery----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }

        Map<String, Object> retMap = new HashMap<String, Object>();
        HashMap<String, Object> paramMap = new HashMap<String, Object>();
        String schemeId = jsonData.getString("followSchemeId");
        if (null == schemeId || "".equals(schemeId)) {
            // 队列下无应用方案，直接返回
            return new ResultModel<Map<String, Object>>(retMap);
        }
        String queueId = jsonData.getString("followQueueId");
        paramMap.put("schemeId", schemeId);
        paramMap.put("queueId", queueId);

        retMap = followQueueSerivce.qryQueueSchemePatientAddContent(paramMap);

        return new ResultModel<Map<String, Object>>(retMap);
    }
}
